import json
import random

from django import http
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User
from apps.verifications import constants
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE
from utils.secret import SecretOauth


class FindPasswordView(View):
    def get(self,request):
        return render(request,'find_password.html')

# /accounts/(?P<username>[a-zA-Z0-9_-]{5,20})/sms/token/
# username(路径参数)	用户名
# image_code(查询参数)	图片验证码
# image_code_id(查询参数)	uuid
class FistFindPasswordView(View):
    def get(self,request,username):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        if not all([username,image_code]):
            return http.HttpResponseForbidden("缺少必传从参数")

        # 保存图片验证码
        from django_redis import get_redis_connection
        redis_client = get_redis_connection('verify_image_code')
        # constants文件里面存在的验证码最大时间 自己写的包
        redis_image_code = redis_client.get('img_%s' % uuid)
        try:
            user = User.objects.get(username = username)
        except:
            return JsonResponse({'status':'5004','errmsg':'用户名或手机号不存在'})
        if redis_image_code is None:
            return JsonResponse({'status':'5001','errmsg':'图形验证码失败'})
        # 响应图片验证码 返回响应对象 图片二进制流
        if image_code.lower() != redis_image_code.decode().lower():
            return JsonResponse({'status':'5001','errmsg':'图形验证码失败'})
        #手机号
        mobile = user.mobile
        random_str = 45964
        redis_client.setex('random_%s' % mobile,300,random_str)
        access_token = SecretOauth().dumps(random_str)
        return JsonResponse({'status':'5000','mobile':mobile,'access_token':access_token})
class TowPasswordView(View):
    def get(self,request,mobile):
        #解密前端标示符
        access_token = request.GET.get('access_token')
        client_token = SecretOauth().loads(access_token)
        #获取后端标示符
        from django_redis import get_redis_connection
        redis_client = get_redis_connection('verify_image_code')
        redis_token = redis_client.get('random_%s' % mobile)
        if client_token != redis_token.decode():
            JsonResponse({'status': '5001', 'message': 'token有误'})

        # 4.生成随机 6位
        sms_code = "%06d" % random.randint(0, 999999)
        # 5.连接验证码reids数据库
        redis_sms_client = get_redis_connection("sms_code")

        # 取出 避免频繁发送短信的标示
        send_flag = redis_sms_client.get("send_flag_%s" % mobile)
        # 如果标识存在
        if send_flag:
            return http.JsonResponse({'status': RETCODE.THROTTLINGERR, 'message': "发送短信过于频繁"})

        # 创建管道
        p1 = redis_sms_client.pipeline()
        # 将redis请求添加到队列里面
        p1.setex('sms_%s' % mobile, 300, sms_code)
        # 将标识缓存起来
        p1.setex('sms_flag_%s' % mobile, 60, 1)
        # 执行请求
        p1.execute()

        # 6.发送短信 --容联云
        from celery_tasks.sms.tasks import send_sms_code_ccp
        # from libs.yuntongxun.sms import CCP
        #                     手机后    6位吗   过期时间   短信模板
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        send_sms_code_ccp.delay(mobile, sms_code)
        # 7.返回响应
        print(sms_code)
        return JsonResponse({'status': '5000', 'message': '发送短信成功'})
class TijiaoPasswordView(View):
    def get(self,request,mobile):
        sms_code = request.GET.get('sms_code')
        print(sms_code)
        #验证用户
        try:
            user= User.objects.get(mobile=mobile)
        except:
            return JsonResponse({'status':'5000'})
        redis_sms_client = get_redis_connection("sms_code")
        redis_sms_code = redis_sms_client.get('sms_%s' % mobile)
        print(redis_sms_code)
        if sms_code != redis_sms_code.decode():
            return JsonResponse({'status': '5001'})
        redis_client = get_redis_connection('verify_image_code')
        redis_token = redis_client.get('random_%s' % mobile)
        access_token = SecretOauth().dumps(redis_token.decode())
        return JsonResponse({'status':'5000','user_id':user.id,'access_token':access_token})
class NewPasswordView(View):
    def post(self,request,user_id):
        json_dict = json.loads(request.body.decode())
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        access_token = json_dict.get('access_token')
        # 解密前端 传入的
        loads_access_token = SecretOauth().loads(access_token)

        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        try:
            user = User.objects.get(id =user_id)
        except:
            return JsonResponse({'status':'5002','message':'user_id有误'})
        redis_client = get_redis_connection('verify_image_code')
        redis_token = redis_client.get('random_%s' % user.mobile)
        print('123',redis_token)
        if loads_access_token != redis_token.decode():
            return JsonResponse({'status': '5001','message':'token有误'})
        # 修改密码
        try:
            user.set_password(password)
            user.save()
        except Exception as e:
            logger.error(e)
        return http.JsonResponse({"status": 5000, 'message': "密码设置成功!"})